import time
from . import ConnPG
import psycopg2
from sanic.log import logger

class UnitTable:

    async def add_unit(self, unit_name):#添加unit

        #参数检查
        if not all([unit_name]):

            return {
                'status': -1,
                'errorCode': 114100,
                'errorMsg': '请检查参数，接口有一个必传参数',
                'resultBody': None
            }

        sql = 'INSERT INTO unit(unit_name) VALUES (%s)'

        try:
            await ConnPG().execute(sql, (unit_name,))
        except psycopg2.errors.UniqueViolation:
            return {

                'status': -1,
                'errorCode': 114101,
                'errorMsg': '当前单位已存在',
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "单位添加成功",
            }
    
    async def select_all_unit(self):#查看所有单位


        sql = 'SELECT * FROM unit'

        result = await ConnPG().fetchall(sql)

        
        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': result,
        }

    async def del_unit(self, unit_id):#删除unit

        #参数检查

        if not unit_id or not unit_id.isdecimal:

            return {
                'status': -1,
                'errorCode': 114100,
                'errorMsg': 'unit_id不能为空且为整数类型',
                'resultBody': None
            }

        sql = 'DELETE FROM unit WHERE id=%s'

        try:
            await ConnPG().execute(sql, (unit_id,))
        except psycopg2.errors.ForeignKeyViolation as e:

            # print(e)

            return {

                'status': -1,
                'errorCode': 300112,
                'errorMsg': str(e),
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "unit删除成功",                                     
            }

    async def update_unit(self, unit_id, unit_name):#更新库房名称

        #参数检查
        if not all([unit_id, unit_name]) or not unit_id.isdecimal():


            return {
                'status': -1,
                'errorCode': 114100,
                'errorMsg': '接口有两个必传参数且unit_id为整数',
                'resultBody': None
            }

        sql = "UPDATE unit SET unit_name=%s WHERE id=%s"


        await ConnPG().execute(sql, (unit_name,unit_id))

    
        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': "unit修改成功",
        }